package com.ruoyi.zsyh.controller.applet.agent;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 大区会长合作商品Controller
 */
@Controller
@RequestMapping("/applet/zsyh/agentCooperate")
public class ZsyhAgentCooperateAppletController extends BaseController
{

    @Autowired
    private IZsyhAgentCooperateService zsyhAgentCooperateService;

    @Autowired
    private IZsyhAgentCooperateRelService zsyhAgentCooperateRelService;

    @Autowired
    private IZsyhPlatformPartsService zsyhPlatformPartsService;

    @Autowired
    private IZsyhPlatformPartstypeService zsyhPlatformPartstypeService;

    @Autowired
    private ISysDtAreaAgentService sysDtAreaAgentService;

    @Autowired
    private IZsyhAgentOrderRelService zsyhAgentOrderRelService;


    /**
     * 获取区域 大区合作产品时
     * @param pId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAreaAgentByPId")
    @ResponseBody
    public AjaxResult getAreaAgentByPId(String pId, String year, String partsId)throws Exception
    {
        SysDtAreaAgent areaAgent = new SysDtAreaAgent();
        areaAgent.setAreaParentId(pId);
        Map map = new HashMap();
        map.put("year", year);
        map.put("partsId", partsId);
        areaAgent.setParams(map);
        return success("成功", sysDtAreaAgentService.selectSysDtAreaAgentList(areaAgent));
    }

    /**
     * 全选二级的时候
     * @param pIds
     * @param year
     * @param partsId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAreaAgentByPIdAll")
    @ResponseBody
    public AjaxResult getAreaAgentByPIdAll(String pIds, String year, String partsId)throws Exception
    {
        SysDtAreaAgent areaAgent = new SysDtAreaAgent();
        Map map = new HashMap();
        map.put("year", year);
        map.put("partsId", partsId);
        map.put("pIds", Convert.toStrArray(pIds));
        areaAgent.setParams(map);
        return success("成功", sysDtAreaAgentService.selectAreaAllByPIds(areaAgent));
    }

    /**
     * 获取单个产品的合作信息
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAgentCooperateById")
    @ResponseBody
    public AjaxResult getAgentCooperateById(String id)throws Exception
    {
        ZsyhAgentCooperate cooperate = zsyhAgentCooperateService.selectZsyhAgentCooperateById(id);
        return success("成功", cooperate);
    }


    /**
     * 获取当个产品的合作区域列表
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAgentCooperateRelById")
    @ResponseBody
    public AjaxResult getAgentCooperateRelById(String id)throws Exception
    {
        ZsyhAgentCooperateRel rel = new ZsyhAgentCooperateRel();
        rel.setCooperateId(id);
        List<ZsyhAgentCooperateRel> list = zsyhAgentCooperateRelService.selectZsyhAgentCooperateRelList(rel);
        return success("成功", list);
    }

    /**
     * 根据产品，区域获取人口总数，目标销售额，保证金
     * @throws Exception
     */
    @RequestMapping("/getSalesBolumeByAgentCooperate")
    @ResponseBody
    public AjaxResult getSalesBolumeByAgentCooperate(String partsId, String areaIds)throws Exception
    {
        if(EmptyUtils.isEmpty(areaIds)){
           return error("未选择区域");
        }
        ZsyhPlatformPartstype parts = zsyhPlatformPartstypeService.selectZsyhPlatformPartstypeById(partsId);
//        ZsyhPlatformParts parts = zsyhPlatformPartsService.selectZsyhPlatformPartsById(partsId);
        String _areaIds[] = areaIds.split(",");
        int peopleNumAll = 0;//区域总人数 万人
        for(String areaId:_areaIds){
            SysDtAreaAgent areaAgent = sysDtAreaAgentService.selectAllAreaAgentById(areaId);
            int peopleNum = areaAgent.getPeopleNum();
            peopleNumAll += peopleNum;
        }
        String populationSalesRatio = parts.getPopulationSalesRatio();//人口销售额比例（每1万人额定销售额）
        String salesPaymentRatio = parts.getSalesPaymentRatio();//销售额定金比例（每1000销售额支付的定金）
        if(EmptyUtils.isEmpty(populationSalesRatio))populationSalesRatio = "0";
        if(EmptyUtils.isEmpty(salesPaymentRatio))salesPaymentRatio = "0";
        BigDecimal populationSalesRatioAll = BigDecimal.ZERO;//总目标销售额
        BigDecimal salesPaymentRatioAll = BigDecimal.ZERO;//销售额保证金

        //总目标销售额  =  人口销售额比例（每1万人额定销售额） * 区域总人数（万人）
        populationSalesRatioAll = new BigDecimal((peopleNumAll * Double.valueOf(populationSalesRatio))).setScale(2, BigDecimal.ROUND_HALF_UP);

        //销售额保证金总额 = 总目标销售额/1000 * 销售额定金比例（每1000销售额支付的定金）
        salesPaymentRatioAll = new BigDecimal(populationSalesRatioAll.doubleValue()/1000 * Double.valueOf(salesPaymentRatio)).setScale(2, BigDecimal.ROUND_HALF_UP);

        Map map = new HashMap();

        map.put("peopleNumAll", peopleNumAll); //区域总人数 万人
        map.put("populationSalesRatioAll", populationSalesRatioAll); //总目标销售额
        map.put("salesPaymentRatioAll", salesPaymentRatioAll);//销售额保证金总额
        map.put("cooperationPolicy", parts.getCooperationPolicy());//政策简介
        return success("成功", map);
    }

    /**
     * 判断这个区域能否选择
     * @throws Exception
     */
    @RequestMapping("/judgeAreaIdIsExist")
    @ResponseBody
    public AjaxResult judgeAreaIdIsExist(String id, String partsId, String areaIds, String year)throws Exception
    {
        String[] _areaIds = areaIds.split(",");
        for(String areaId:_areaIds){
            ZsyhAgentCooperateRel cooperateRel = new ZsyhAgentCooperateRel();
            cooperateRel.setYear(year);
            cooperateRel.setDistrict(areaId);
            cooperateRel.setPartsId(partsId);
            List<ZsyhAgentCooperateRel> list = zsyhAgentCooperateRelService.selectZsyhAgentCooperateRelList(cooperateRel);
            if(list.size() > 0){
                String cooperateId = list.get(0).getCooperateId();
                if(!cooperateId.equals(id)){//自己修改自己的
//                    return error(list.get(0).getProvinceName() + list.get(0).getCityName() + list.get(0).getDistrictName() + "已有合作大区，请刷新后更换地区");
                    return error("区域已有合作大区，请刷新后更换地区");
                }
            }
        }

        return success("成功", 0);
    }

    /**
     * 申请产品合作 大区会长
     * @throws Exception
     */
    @RequestMapping("/applyAgentCooperate")
    @ResponseBody
    public AjaxResult applyAgentCooperate(String agentId, String partsId, String areaIds, String peopleNum, String salesVolume, String earnestMoney, String year)throws Exception    {
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }

        ZsyhPlatformPartstype parts = zsyhPlatformPartstypeService.selectZsyhPlatformPartstypeById(partsId);
//        ZsyhPlatformParts parts = zsyhPlatformPartsService.selectZsyhPlatformPartsById(partsId);

        ZsyhAgentCooperate agentCooperate = new ZsyhAgentCooperate();
        agentCooperate.setId(IdWorker.getId());
        agentCooperate.setAgentId(agentId);
        agentCooperate.setPartsId(partsId);
        agentCooperate.setPeopleNum(Integer.valueOf(peopleNum));
        agentCooperate.setSalesVolume(new BigDecimal(salesVolume));
        agentCooperate.setEarnestMoney(new BigDecimal(earnestMoney));
        agentCooperate.setCooperationPolicy(parts.getCooperationPolicy());
        agentCooperate.setPopulationSalesRatio(parts.getPopulationSalesRatio());
        agentCooperate.setSalesPaymentRatio(parts.getSalesPaymentRatio());
        agentCooperate.setYear(year);
        zsyhAgentCooperateService.insertZsyhAgentCooperateApplet(agentCooperate);

        String _areaIds[] = areaIds.split(",");
        for(String areaId:_areaIds){
            SysDtAreaAgent areaAgent = sysDtAreaAgentService.selectAllAreaAgentById(areaId);
            ZsyhAgentCooperateRel cooperateRel = new ZsyhAgentCooperateRel();
            cooperateRel.setId(IdWorker.getId());
            cooperateRel.setCooperateId(agentCooperate.getId());
            cooperateRel.setAgentId(agentId);
            cooperateRel.setPartsId(partsId);
            cooperateRel.setYear(year);
            cooperateRel.setProvince(areaAgent.getProvinceId());
            cooperateRel.setProvinceName(areaAgent.getAreaName());
            cooperateRel.setCity(areaAgent.getAreaParentId());
            cooperateRel.setCityName(areaAgent.getSecondAreaName());
            cooperateRel.setDistrict(areaAgent.getId());
            cooperateRel.setDistrictName(areaAgent.getThirdAreaName());
            cooperateRel.setPeopleNum(areaAgent.getPeopleNum());
            zsyhAgentCooperateRelService.insertZsyhAgentCooperateRel(cooperateRel);

        }
        return success("成功");
    }


    /**
     * 修改 申请产品合作 大区会长
     * @throws Exception
     */
    @RequestMapping("/updateAgentCooperate")
    @ResponseBody
    public AjaxResult updateAgentCooperate(String id, String agentId, String partsId, String areaIds, String peopleNum, String salesVolume, String earnestMoney, String year)throws Exception    {
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }
        ZsyhPlatformPartstype parts = zsyhPlatformPartstypeService.selectZsyhPlatformPartstypeById(partsId);
//        ZsyhPlatformParts parts = zsyhPlatformPartsService.selectZsyhPlatformPartsById(partsId);

        ZsyhAgentCooperate agentCooperate = new ZsyhAgentCooperate();
        agentCooperate.setId(id);
        agentCooperate.setAgentId(agentId);
        agentCooperate.setPartsId(partsId);
        agentCooperate.setPeopleNum(Integer.valueOf(peopleNum));
        agentCooperate.setSalesVolume(new BigDecimal(salesVolume));
        agentCooperate.setEarnestMoney(new BigDecimal(earnestMoney));
        agentCooperate.setCooperationPolicy(parts.getCooperationPolicy());
        agentCooperate.setPopulationSalesRatio(parts.getPopulationSalesRatio());
        agentCooperate.setSalesPaymentRatio(parts.getSalesPaymentRatio());
        agentCooperate.setYear(year);
        zsyhAgentCooperateService.updateZsyhAgentCooperate(agentCooperate);


        //删除原有的地区信息
        zsyhAgentCooperateRelService.deleteZsyhAgentCooperateRelByCooperateId(id);
        //添加新的地区信息
        String _areaIds[] = areaIds.split(",");
        for(String areaId:_areaIds){
            SysDtAreaAgent areaAgent = sysDtAreaAgentService.selectAllAreaAgentById(areaId);
            ZsyhAgentCooperateRel cooperateRel = new ZsyhAgentCooperateRel();
            cooperateRel.setId(IdWorker.getId());
            cooperateRel.setCooperateId(agentCooperate.getId());
            cooperateRel.setAgentId(agentId);
            cooperateRel.setPartsId(partsId);
            cooperateRel.setYear(year);
            cooperateRel.setProvince(areaAgent.getProvinceId());
            cooperateRel.setProvinceName(areaAgent.getAreaName());
            cooperateRel.setCity(areaAgent.getAreaParentId());
            cooperateRel.setCityName(areaAgent.getSecondAreaName());
            cooperateRel.setDistrict(areaAgent.getId());
            cooperateRel.setDistrictName(areaAgent.getThirdAreaName());
            cooperateRel.setPeopleNum(areaAgent.getPeopleNum());
            zsyhAgentCooperateRelService.insertZsyhAgentCooperateRel(cooperateRel);

        }
        return success("成功");
    }


    /**
     * 获取大区会长合作产品列表
     * @throws Exception
     */
    @RequestMapping("/getAgentCooperateListByAgentId")
    @ResponseBody
    public AjaxResult getAgentCooperateListByAgentId(String agentId, String year, String key)throws Exception    {
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }
        ZsyhAgentCooperate agentCooperate = new ZsyhAgentCooperate();
        agentCooperate.setAgentId(agentId);
        agentCooperate.setYear(year);
        agentCooperate.setPartsName(key);
        return success("成功", zsyhAgentCooperateService.selectZsyhAgentCooperateList(agentCooperate));
    }


    /**
     * 获取大区会长 年度任务 完成比例
     * @throws Exception
     */
    @RequestMapping("/getAgentTaskProportion")
    @ResponseBody
    public AjaxResult getAgentCooperateListByAgentId(String agentId, String year)throws Exception    {
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }
        if(EmptyUtils.isEmpty(year)){
            year = String.valueOf(DateUtils.getYear());
        }
        Map map = new HashMap();
        map.put("agentId", agentId);
        map.put("year", year);
        map.put("incomplete", "1");
        Map agentTaskAllMap = zsyhAgentOrderRelService.getAgentTaskAll(map);//订货金额
        Map agentTargetAllMap = zsyhAgentCooperateService.getAgentTargetAll(map);//目标销售额
        List<Map> partsSalesVolumeAll = zsyhPlatformPartsService.getPartsSalesVolumeAll(map);


        BigDecimal agentTaskAll = new BigDecimal(String.valueOf(agentTaskAllMap.get("money")));
        BigDecimal salesVolumeAll = new BigDecimal(String.valueOf(agentTargetAllMap.get("salesVolume")));
        BigDecimal earnestMoneyAll = new BigDecimal(String.valueOf(agentTargetAllMap.get("earnestMoney")));


        Map map1 = new HashMap();
        map1.put("text", year + "年度("+year+".1.1 - "+year+".12.31)任务进度");
        map1.put("agentTaskAll", agentTaskAll);//已完成的订货金额 万元
        map1.put("salesVolumeAll", salesVolumeAll);//目标总金额 万元
        map1.put("earnestMoneyAll", earnestMoneyAll);//定金
        map1.put("incompleteNum", partsSalesVolumeAll.size());//定金


        if(salesVolumeAll.doubleValue() > 0){
            BigDecimal ratio = agentTaskAll.divide(salesVolumeAll, 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            map1.put("ratio", ratio);//完成比例
        }else{
            map1.put("ratio", 0);//完成比例
        }
        return success("成功", map1);
    }


    /**
     * 获取大区会长 年度任务 任务进度详情
     * @throws Exception
     */
    @RequestMapping("/getAgentTaskProportionDetails")
    @ResponseBody
    public AjaxResult getAgentTaskProportionDetails(String agentId, String year, String key)throws Exception    {
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }
        if(EmptyUtils.isEmpty(year)){
            year = String.valueOf(DateUtils.getYear());
        }
        Map map = new HashMap();
        map.put("agentId", agentId);
        map.put("year", year);
        map.put("key", key);
        List<Map> partsSalesVolumeAll = zsyhPlatformPartsService.getPartsSalesVolumeAll(map);

        return success("成功", partsSalesVolumeAll);
    }
}
